import LoginServiceApi from '@/views/auth/login/assets/loginServiceApi'
import { doLoginOut, setToken } from '@/token'
import { encrypt } from '@/views/auth/login/assets/encrypt'
import { MessageBox } from 'element-ui'

export default {
  namespaced: true,
  state: {
    routingAddress: [],
    isAdmin: false,
    userInfo: null
  },
  mutations: {
    SET_ROUTING_ADDRESS(state, routingAddress = []) {
      state.routingAddress = routingAddress
    },
    SET_IS_ADMIN(state, isAdmin = false) {
      state.isAdmin = isAdmin
    },
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
    }
  },
  actions: {
    doLogout() {
      return MessageBox.confirm('确定退出系统吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        doLoginOut()
        window.location.href = window.__CTC_ENV__.VUE_APP_LOGOUT_URL
      })
    },
    doLogin({ commit }, { username, password, code, uuid }) {
      return LoginServiceApi.authLogin({ username, password: encrypt(password), code, uuid }).then(({ data }) => {
        const token = data?.access_token
        setToken(token)
        return token
      })
    },
    /**
     * 获取用户信息 菜单列表
     * @param commit
     * @returns {Promise<Awaited<void>[]>}
     */
    fetchUserInfo({ commit }) {
      const userInfo = LoginServiceApi.getUserInfo().then(res => {
        const user = res?.data
        commit('SET_USER_INFO', user)
        return user
      })
      const routers = LoginServiceApi.getRouters().then(res => {
        const routers = res?.data || []
        commit('SET_ROUTING_ADDRESS', routers)
        return routers
      })
      return Promise.all([userInfo, routers])
    }
  },
  getters: {
    routingAddress: state => state.routingAddress,
    isAdmin: state => state.isAdmin,
    userInfo: state => state.userInfo
  }
}
